package com.flowershop.dao;

import com.flowershop.model.Order;
import com.flowershop.model.OrderItem;
import com.flowershop.util.DBUtil;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class OrderDao {
    
    public Order createOrder(Order order) {
        String sql = "INSERT INTO orders (user_id, total_amount, status) VALUES (?, ?, ?)";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {
            
            pstmt.setInt(1, order.getUserId());
            pstmt.setBigDecimal(2, order.getTotalAmount());
            pstmt.setString(3, order.getStatus());
            
            pstmt.executeUpdate();
            
            ResultSet rs = pstmt.getGeneratedKeys();
            if (rs.next()) {
                order.setId(rs.getInt(1));
                // 创建订单项
                createOrderItems(order.getId(), order.getItems());
                return order;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    
    private void createOrderItems(Integer orderId, List<OrderItem> items) {
        String sql = "INSERT INTO order_items (order_id, flower_id, quantity, price) VALUES (?, ?, ?, ?)";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            
            for (OrderItem item : items) {
                pstmt.setInt(1, orderId);
                pstmt.setInt(2, item.getFlowerId());
                pstmt.setInt(3, item.getQuantity());
                pstmt.setBigDecimal(4, item.getPrice());
                pstmt.addBatch();
            }
            
            pstmt.executeBatch();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    public List<Order> getOrdersByUserId(Integer userId) {
        List<Order> orders = new ArrayList<>();
        String sql = "SELECT * FROM orders WHERE user_id = ? ORDER BY create_time DESC";
        
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            
            pstmt.setInt(1, userId);
            ResultSet rs = pstmt.executeQuery();
            
            while (rs.next()) {
                Order order = new Order();
                order.setId(rs.getInt("id"));
                order.setUserId(rs.getInt("user_id"));
                order.setTotalAmount(rs.getBigDecimal("total_amount"));
                order.setStatus(rs.getString("status"));
                order.setCreateTime(rs.getTimestamp("create_time"));
                order.setUpdateTime(rs.getTimestamp("update_time"));
                
                // 获取订单项
                order.setItems(getOrderItems(order.getId()));
                orders.add(order);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        return orders;
    }
    
    private List<OrderItem> getOrderItems(Integer orderId) {
        List<OrderItem> items = new ArrayList<>();
        String sql = "SELECT oi.*, f.name as flower_name, f.image_url " +
                    "FROM order_items oi " +
                    "JOIN flowers f ON oi.flower_id = f.id " +
                    "WHERE oi.order_id = ?";
        
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            
            pstmt.setInt(1, orderId);
            ResultSet rs = pstmt.executeQuery();
            
            while (rs.next()) {
                OrderItem item = new OrderItem();
                item.setId(rs.getInt("id"));
                item.setOrderId(rs.getInt("order_id"));
                item.setFlowerId(rs.getInt("flower_id"));
                item.setQuantity(rs.getInt("quantity"));
                item.setPrice(rs.getBigDecimal("price"));
                item.setFlowerName(rs.getString("flower_name"));
                item.setImageUrl(rs.getString("image_url"));
                items.add(item);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        return items;
    }
    
    public boolean updateOrderStatus(Integer orderId, String status) {
        String sql = "UPDATE orders SET status = ? WHERE id = ?";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            
            pstmt.setString(1, status);
            pstmt.setInt(2, orderId);
            return pstmt.executeUpdate() > 0;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
    
    public List<Order> getAllOrders() {
        List<Order> orders = new ArrayList<>();
        String sql = "SELECT o.*, u.username FROM orders o " +
                    "JOIN users u ON o.user_id = u.id " +
                    "ORDER BY o.create_time DESC";
        
        try (Connection conn = DBUtil.getConnection();
             Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery(sql)) {
            
            while (rs.next()) {
                Order order = new Order();
                order.setId(rs.getInt("id"));
                order.setUserId(rs.getInt("user_id"));
                order.setTotalAmount(rs.getBigDecimal("total_amount"));
                order.setStatus(rs.getString("status"));
                order.setCreateTime(rs.getTimestamp("create_time"));
                order.setUpdateTime(rs.getTimestamp("update_time"));
                order.setUsername(rs.getString("username"));
                
                // 获取订单项
                order.setItems(getOrderItems(order.getId()));
                orders.add(order);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        return orders;
    }
} 